/**
 * Copyright (C) 2010-2011 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.seequencer.client;

import java.util.ArrayList;

import org.seequencer.client.common.SwissKnife;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.IsWidget;

public class MasterController {
	
	private boolean play = false;
	
	private Timer masterTimer;

	private int currentBpm = 100;

	private int currentPositionInSong = 0;

	private boolean loopMode = true;

	private int loopBegin = 0;

	private int loopEnd = 15;

	private ArrayList<InstrumentLane> instrumentLanes;

	public interface View {

		HasClickHandlers getStartButtonClickHandler();

		String getBpmSetInTextArea();

		boolean isLoopMode();

		String getLoopBeginTextArea();

		String getLoopEndTextArea();

		void setCurrentPositionLabel(String currentPosition);

		IsWidget asWidget();
	}

	private MasterController.View view;

	public MasterController(MasterController.View view) {
		this.view = view;

		instrumentLanes = new ArrayList<InstrumentLane>();
		doBind();

	}
	
	
	void doBind() {
		
		view.getStartButtonClickHandler().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				
				if (play) {
					play = false;
					masterTimer.cancel();
				} else {		
					play = true;
					startTimerAndPlaySong();
				}
				
			}
		});
		
	}

	public void addInstrumentLane(InstrumentLane instrumentLane) {
		instrumentLanes.add(instrumentLane);
	}

	public void startTimerAndPlaySong() {

		masterTimer = new Timer() {

			@Override
			public void run() {
				
				view.setCurrentPositionLabel(""+currentPositionInSong);
				
				for (InstrumentLane instrumentLane : instrumentLanes) {

					instrumentLane.playIfNoteAtPosition(currentPositionInSong);

				}
				
				
				if (loopMode) {
					if (currentPositionInSong >= loopEnd) {

						currentPositionInSong = loopBegin;

					} else {
						currentPositionInSong++;
					}

				} else {
					currentPositionInSong++;
				}

			}

		};

		masterTimer.scheduleRepeating(SwissKnife.fromBpmToMs(currentBpm));

	}

	public IsWidget asWidget() {
		return view.asWidget();
	}

}
